import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import md5 from 'md5';
import moment from 'moment';
import { createToken } from '../auth.js';

const router = new Router();
router.prefix('/api');

router.post('/oper/login', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail('缺少必填字段 帐号');
        return;
    }
    let joinParam = [
        {
            fields: 'oper.*,role.role_name,role.role_value',
            table: 'role',
            on: 'oper.role_id=role.id',
        },
    ];

    let { count, rows } = await db.findAll('oper', { account: body.account }, null, 'desc', 1, 0, null, null, joinParam);
    if (count == 0) {
        ctx.body = response.fail('帐号不存在');
        return;
    }
    let oper = rows[0];
    if (oper.password == null) oper.password = '';
    if (oper.password == '' || oper.password == md5(body.password)) {
        const { token, expireTime } = await createToken({
            account: oper.account,
            name: oper.name,
            role_id: oper.role_id,
        });
        oper.token = token;
        oper.expireTime = expireTime;
        delete oper.password;
        await db.update('oper', { last_login: moment().format('YYYY-MM-DD HH:mm:ss') }, { account: body.account });
        ctx.body = response.success(oper);
        return;
    } else {
        ctx.body = response.fail('密码错误');
    }
});

router.post('/openid/login', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.openid == null) {
        ctx.body = response.fail('缺少必填字段 openid');
        return;
    }
    if(body.password == null){
        ctx.body = response.fail('缺少必填字段 密码');
        return;
    }
    if(body.password != '123456'){
        ctx.body = response.fail('密码错误');
        return;
    }

    const { token, expireTime } = await createToken({
        openid: body.openid
    });
    let data={token:token,expireTime:expireTime};

    ctx.body = response.success(data);
})

router.post('/oper/add', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let isExist = await db.findOne('oper', { account: body.account });
    if (isExist != null) {
        ctx.body = response.fail('相同帐号已存在');
        return;
    }
    if (body.password != null) {
        body.password = md5(body.password);
    }
    body.create_time = moment().format('YYYY-MM-DD HH:mm:ss');
    body.create_oper = ctx.state.oper.name;
    let res = await db.create('oper', body);
    if (res instanceof Error) {
        logger.error(`oper create error :` + res.message);
        ctx.body = response.fail(`oper create error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/edit', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail('缺少必填字段 帐号');
        return;
    }
    let obj = await db.findOne('oper', { account: body.account });
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    for (let key in body) {
        if (body[key] != undefined) {
            if (key == 'password') {
                //  obj[key] = md5(body[key]);
            } else {
                obj[key] = body[key];
            }
        }
    }
    let res = await db.update('oper', obj, { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper update error :` + res.message);
        ctx.body = response.fail(`oper update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/delete', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail('缺少必填字段 帐号');
        return;
    }
    let res = await db.deleteRow('oper', { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper delete error :` + res.message);
        ctx.body = response.fail(`oper delete error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/oper/list', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    let res = await db.findAll(
        'oper',
        body.conditions,
        body.orderBy,
        body.direction,
        body.limit,
        body.offset,
        body.areaArr,
        body.likeArr,
        body.leftJoinArr,
        body.inArr,
        'account,name,type,type,role_id,phone,openid,last_login,merchant_id'
    );
    if (res instanceof Error) {
        logger.error(`oper getList error :` + res.message);
        ctx.body = response.fail(`oper getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
    } else {
        ctx.body = response.success({ rows: res });
    }
});

router.post('/oper/changePass', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail('缺少必填字段 帐号');
        return;
    }
    if (body.oldPass == null) {
        ctx.body = response.fail('缺少必填字段 旧密码');
        return;
    }
    if (body.newPass == null) {
        ctx.body = response.fail('缺少必填字段 新密码');
        return;
    }
    let oper = await db.findOne('oper', { account: body.account });
    if (oper == null) {
        ctx.body = response.fail('帐号不存在');
        return;
    }
    if (oper.password == '' || oper.password == md5(body.oldPass) || oper.password == null) {
        oper.password = md5(body.newPass);
        let res = await db.update('oper', oper, { account: body.account });
        if (res instanceof Error) {
            logger.error(`oper update error :` + res.message);
            ctx.body = response.fail(`change password update error :` + res.message);
            return;
        }
        ctx.body = response.success();
    } else {
        ctx.body = response.fail('旧密码错误');
    }
});

router.post('/oper/resetPass', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail('缺少必填字段 帐号');
        return;
    }
    let oper = await db.findOne('oper', { account: body.account });
    if (oper == null) {
        ctx.body = response.fail('帐号不存在');
        return;
    }
    oper.password = md5('123456');
    let res = await db.update('oper', oper, { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper update error :` + res.message);
        ctx.body = response.fail(`reset password update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});



export { router };
